const express = require('express');
const router = express.Router();
const authenticateToken = require('../middleware/auth');

// 智能回复规则
const autoReplies = {
  '订单': '您可以在"我的订单"中查看订单状态，或告诉我您的订单号，我来帮您查询。',
  '物流': '请提供您的订单号，我来帮您查询物流信息。',
  '退货': '退货流程：1.进入订单详情 2.申请退货 3.等待审核 4.寄回商品。需要帮助吗？',
  '优惠券': '您可以在"我的优惠券"中查看可用优惠券，或者关注我们的活动获取更多优惠。',
  '账户': '账户相关问题我可以帮您处理，请详细描述您遇到的问题。',
  '支付': '支付问题请检查：1.网络连接 2.支付方式 3.账户余额。仍有问题请联系人工客服。'
};

// 建立客服连接
router.post('/connect', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 记录用户连接
    const query = `
      INSERT INTO customer_service_sessions (user_id, status, created_at)
      VALUES (?, 'active', NOW())
      ON DUPLICATE KEY UPDATE status = 'active', updated_at = NOW()
    `;
    
    await global.db.execute(query, [userId]);
    
    res.json({
      message: '连接成功',
      sessionId: `session_${userId}_${Date.now()}`
    });
  } catch (error) {
    console.error('建立客服连接失败:', error);
    res.status(500).json({ message: '连接失败' });
  }
});

// 发送消息
router.post('/message', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { message, type = 'text' } = req.body;
    
    if (!message) {
      return res.status(400).json({ message: '消息内容不能为空' });
    }
    
    // 保存用户消息
    const saveMessageQuery = `
      INSERT INTO customer_service_messages 
      (user_id, content, sender_type, message_type, created_at)
      VALUES (?, ?, 'user', ?, NOW())
    `;
    
    await global.db.execute(saveMessageQuery, [userId, message, type]);
    
    // 智能回复逻辑
    let reply = null;
    let replyType = 'auto';
    
    // 检查是否匹配自动回复规则
    for (const [keyword, response] of Object.entries(autoReplies)) {
      if (message.includes(keyword)) {
        reply = response;
        break;
      }
    }
    
    // 如果没有匹配到自动回复，使用默认回复
    if (!reply) {
      reply = '感谢您的咨询，我已收到您的问题，正在为您查询相关信息，请稍等...';
    }
    
    // 保存客服回复
    if (reply) {
      const saveReplyQuery = `
        INSERT INTO customer_service_messages 
        (user_id, content, sender_type, message_type, created_at)
        VALUES (?, ?, 'service', 'text', NOW())
      `;
      
      await global.db.execute(saveReplyQuery, [userId, reply]);
    }
    
    res.json({
      message: '消息发送成功',
      reply: reply,
      type: replyType
    });
    
  } catch (error) {
    console.error('发送消息失败:', error);
    res.status(500).json({ message: '发送失败' });
  }
});

// 获取聊天历史
router.get('/history', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { limit = 50, offset = 0 } = req.query;
    
    const query = `
      SELECT id, content, sender_type, message_type, created_at
      FROM customer_service_messages 
      WHERE user_id = ?
      ORDER BY created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    const [rows] = await global.db.execute(query, [userId, parseInt(limit), parseInt(offset)]);
    
    const messages = rows.map(row => ({
      id: row.id.toString(),
      content: row.content,
      isCustomer: row.sender_type === 'user',
      time: new Date(row.created_at).toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      }),
      type: row.message_type
    })).reverse();
    
    res.json({
      messages: messages,
      total: rows.length
    });
    
  } catch (error) {
    console.error('获取聊天历史失败:', error);
    res.status(500).json({ message: '获取失败' });
  }
});

module.exports = router;

